package com.example.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.Permission;
import com.example.domain.User;
import com.example.mapper.UserMapper;
import com.example.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@EnableWebSecurity
public class MybatisPlusUserDetailservice implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        //根据手机号登录，所以这里的登录账号我从用户名改成了手机号，类的名字我就不改了
        System.out.println(phone);
        User login = userMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));


//        List list=new ArrayList();

        if (login!=null){

            List<Permission> permissions = permissionMapper.selectByUserId(login.getUid());

            List<GrantedAuthority> list = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());

            UserDetails user = new org.springframework.security.core.userdetails.User(phone, login.getPassword(),list);
            return user;
        }

        return null;
    }
}
